﻿using System.Collections.Generic;
using System.Linq;
using Missbot.Common;
using Missbot.Service;

namespace Missbot.AIModule.Gaming.Lottery
{
    public class LotteryPersonRecord : DbBaseEntity
    {
        public string UserID { get; init; }

        public Dictionary<string, int> LotteryDic { get; set; } = new();
    }

    public static class LotteryPersonDA
    {
        public static LotteryPersonRecord Get(string UserID)
        {
            var record = MongoService<LotteryPersonRecord>.GetOnly(p => p.UserID == UserID);
            if (record != null)
            {
                return record;
            }

            record = new LotteryPersonRecord { UserID = UserID };
            MongoService<LotteryPersonRecord>.Insert(record);
            return record;
        }

        public static void Update(this LotteryPersonRecord entity)
        {
            MongoService<LotteryPersonRecord>.Update(entity);
        }

        public static void AddLottery(this LotteryPersonRecord entity, string LotteryName)
        {
            if (!entity.LotteryDic.ContainsKey(LotteryName))
            {
                entity.LotteryDic.Add(LotteryName, 0);
            }

            entity.LotteryDic[LotteryName]++;
        }

        public static string Format(this LotteryPersonRecord entity)
        {
            var LotteryMgr = AutofacSvc.Resolve<LotterySvc>();
            var ordered = entity.LotteryDic.Select(p => new { Model = LotteryMgr[p.Key], Count = p.Value }).OrderByDescending(p => p.Model.Bonus).ToList();
            var str = string.Join("\n", ordered.Select(p => $"{p.Model.Name}({p.Model.Bonus.CurencyFormat()})*{p.Count}次"));
            str += $"\n总计{ordered.Sum(p => p.Count)}次";
            str += $"\n总盈亏{ordered.Sum(p => (p.Model.Bonus - LotterySvc.LotteryFee) * p.Count).CurencyFormat()}";

            return str;
        }
    }
}